#!/bin/sh

self="$(cd "$(dirname "$0")" ; pwd)/$(basename "$0")"
findexpr="( \
-name *.[CcHh] -o \
-name *.cc     -o -name *.hh -o \
-name *.[ch]pp -o -name *.[ch]xx \
)"

cmd="$1" ; shift

case "$cmd" in
    --extract-includes)
        includes=""
        sep=""

        prefix='^[[:blank:]]*#[[:blank:]]*include[[:blank:]]*"'
        suffix='"[[:blank:]]*$'
        sedaddr="/${prefix}.*${suffix}/"
        sedexpr="s/${prefix}(.+)${suffix}/\\1/gp"

        for srcfile ; do
            for incfile in $(sed -En "${sedaddr}${sedexpr}" "$srcfile") ; do
                dirpath="$(dirname "$srcfile")"
                while : ; do
                    case "$incfile" in
                        ../*)
                            dirpath=${dirpath%/*}
                            incfile=${incfile#*/}
                            ;;

                        *)
                            break
                            ;;
                    esac
                done

                incfile="${dirpath}/${incfile}"
                includes="${includes}${sep}${incfile}"
                sep=" "
            done
        done

        echo "${srcfile}: $includes; @touch \$@"
        ;;

    *)
        set -- "$cmd" "$@"
        echo '## This file is automatically generated by "gen-inc-dep.sh" ##'
        find "$@" $findexpr -exec "$self" --extract-includes {} \;
        ;;
esac
